/*
 * File:   ipc_receiver.cpp
 * Author: dolphinigle
 *
 * Created on December 2, 2011, 4:14 PM
 */

#include "ipc_manager.h"
#include "ipc_receiver.h"
#include "file_system.h"

#include <string>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/msg.h>
using std::string;

IPCReceiver::IPCReceiver(
    const string& filename, int to_receiver_msq_key,
    int from_receiver_msq_key) {
  // Preparing message queue.
  int msg_flag = 0666;

  int to_receiver = msgget(to_receiver_msq_key, msg_flag);
  if (to_receiver < 0) {
    // Failed
    printf("msgget error in receiver\n");
    exit(4);
  }

  int from_receiver = msgget(from_receiver_msq_key, msg_flag);
  if (from_receiver < 0) {
    // Failed
    printf("msgget error in receiver\n");
    exit(4);
  }

  IPCManager manager(from_receiver, to_receiver);
  FileSystem fs(filename);

  while (true) {
    string msg = manager.ReceiveMessage();
    if (msg == "isexist") {
      string path = manager.ReceiveMessage();
      manager.SendMessage(fs.IsExist(path));
    } else if (msg == "ls") {
      string path = manager.ReceiveMessage();
      manager.SendMessage(fs.Ls(path));
    } else if (msg == "mkdir") {
      string path = manager.ReceiveMessage();
      manager.SendMessage(fs.Mkdir(path));
    } else if (msg == "rm") {
      string path = manager.ReceiveMessage();
      manager.SendMessage(fs.Rm(path));
    } else if (msg == "cp1") {
      string path1 = manager.ReceiveMessage();
      string path2 = manager.ReceiveMessage();
      manager.SendMessage(fs.Cp1(path1, path2));
    } else if (msg == "cp2") {
      string path1 = manager.ReceiveMessage();
      string path2 = manager.ReceiveMessage();
      manager.SendMessage(fs.Cp2(path1, path2));
    } else if (msg == "cat") {
      string path = manager.ReceiveMessage();
      manager.SendMessage(fs.Cat(path));
    } else if (msg == "close") {
      manager.SendMessage(fs.Close());
      break;
    } else if (msg == "status") {
      manager.SendMessage(fs.Status());
    }
  }

  exit(0);
}

